package com.tjcd.project.library_base.base.fragment;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PathUtils;
import com.huantansheng.easyphotos.EasyPhotos;
import com.mylhyl.circledialog.CircleDialog;
import com.tjcd.project.library_base.R;
import com.tjcd.project.library_base.base.activity.BaseNetActivity;
import com.tjcd.project.library_base.base.bean.ItemChooseBean;
import com.tjcd.project.library_base.base.utils.GlideEngine;
import com.tjcd.project.library_base.common.baseBean.OssUploadFileBean;
import com.tjcd.project.library_base.common.upload.bean.CommonFileBean;
import com.tjcd.project.library_base.common.upload.bean.UploadBean;
import com.tjcd.project.library_base.common.upload.contract.FileUploadContract;
import com.tjcd.project.library_base.common.upload.presenter.FileUploadPresenter;
import com.tjcd.project.library_base.common.utils.OssUpLoadUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * @Author jiangKunKun
 * @CreateDate 2023/1/12
 * @Description
 * @SpittingGrooves
 */
public abstract class BaseFileUploadFragment <V extends ViewDataBinding> extends BaseNetActivity<V> implements FileUploadContract.View{
    // 文件上传
    protected FileUploadPresenter mFileUploadPresenter;
    // 正在上传
    protected boolean isUploading;
    // oss上传bean
    private OssUploadFileBean mOssUploadFileBean;
    // 文件
    private File mFile;
    // 类型
    private String mType;
    // 选择
    private CircleDialog.Builder mDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFileUploadPresenter = new FileUploadPresenter();
        mFileUploadPresenter.attachView(activity);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mFileUploadPresenter.detachView();
    }

    protected void showPicPop(int type) {
        final List<ItemChooseBean> rvListForV = new ArrayList<>();
        rvListForV.add(new ItemChooseBean(1, "拍照"));
        rvListForV.add(new ItemChooseBean(2, "相册"));
        if (mDialog == null) {
            mDialog = new CircleDialog.Builder()
                    .configDialog(params -> params.animStyle = R.style.PopupWindowBottimAnimation)
                    .configItems(params -> {
                        params.itemHeight = 55;
                        params.textSize = 16;
                        params.dividerHeight = 1;
                        params.textColor = getResources().getColor(R.color.black_000000);
                    })
                    .setNegative("取消", null)
                    .configNegative(params -> {
                        params.textSize = 16;
                        params.topMargin = 10;
                        params.height = 55;
                        params.textColor = getResources().getColor(R.color.black_000000);
                    });
        }
        mDialog.setItems(rvListForV, (view, position) -> {
            if (position == 0) {
                // 拍照
                photograph(type);
            } else if (1 == position) {
                // 相册
                photoAlbum(type);
            }
            mDialog.dismiss();
            return false;
        });
        mDialog.show(getSupportFragmentManager());
    }

    protected void photoAlbum(int type) {
        EasyPhotos.createAlbum(activity, false, false, GlideEngine.getInstance())
                .setFileProviderAuthority(getPackageName() + ".fileprovider")
                .start(type);//也可以选择链式调用写法
    }

    protected void photograph(int type) {
        EasyPhotos.createCamera(activity, true)
                .setFileProviderAuthority(getPackageName() + ".fileprovider")
                .start(type);//也可以选择链式调用写法
    }

    /**
     * 压缩图片
     *
     * @param item
     * @param type
     */
    protected void compreeImg(CommonFileBean item, String type) {
        Luban.with(activity).load(item.getPath()).ignoreBy(200).setTargetDir(PathUtils.getExternalStoragePath())
                .setCompressListener(new OnCompressListener() {

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        LogUtils.e("压缩成功" + file.getPath());
                        isUploading = true;
                        mFile = file;
                        mType = type;
                        mFileUploadPresenter.fileUploadOss(file, type);
                        // 换为oss

//                        mFileUploadPresenter.fileUploadProgress(file, type, new FileUploadObserver<BaseDataBean<String>>() {
//                            @Override
//                            public void onUpLoadSuccess(BaseDataBean<String> stringBaseDataBean) {
//
//                            }
//
//                            @Override
//                            public void onUpLoadFail(Throwable e) {
//
//                            }
//
//                            @Override
//                            public void onProgress(int progress) {
//
//                            }
//                        });
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("压缩失败" + e.toString());
                        isUploading = true;
                        mFile = new File(item.getPath());
                        mType = type;
                        mFileUploadPresenter.fileUploadOss(mFile, type);
                    }
                }).launch();
    }

    @Override
    public void fileUploadOssSuc(OssUploadFileBean uploadBean, File file, String type) {
        LogUtils.e("获取oss签名成功");
        mOssUploadFileBean = uploadBean;
        if (null != mOssUploadFileBean) {
            upFile();
        } else {
            mFileUploadPresenter.fileUploadOss(file, type);
        }
    }

    @Override
    public abstract void fileUploadSuc(UploadBean uploadBean, String type);

    @Override
    public abstract void fileUploadFai(String type);

    @Override
    public void fileUploadOssFail(File file, String type) {
        LogUtils.e("获取oss签名失败");
    }

    private void upFile() {
        if (null == mOssUploadFileBean) {
            return;
        }
        new OssUpLoadUtil().ossUpLoadFile(mOssUploadFileBean, mFile, new OssUpLoadUtil.ossUpLoadListener() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

            }

            @Override
            public void onSingleSuccess(PutObjectRequest request, PutObjectResult result) {

            }

            @Override
            public void onAllSuccess(ArrayList<UploadBean> objectKey) {
                LogUtils.e("文件上传成功" + mFile.toString());
                for (UploadBean uploadBean : objectKey) {
                    fileUploadSuc(uploadBean, mType);
                }

            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                fileUploadFai(mType);
            }
        });
    }

    /**
     * 提示文件上传失败
     *
     * @param type
     */
    protected void showFileUploadError(String type) { // 失败提示
        switch (type) {
//            case FileConfig.DRIVER_AVATAR: // 司机头像照片  fileUploadFai调用
//                ToastUtils.showLong("司机头像照片上传失败,请重新上传");
//                break;
            default:
        }
    }
}
